#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include "scripts.h"  // JavaScript code
#include "css.h"      // Cascading Style Sheets
#include "html.h"     // HTML page of the tool
#include "epd.h"      // e-Paper driver

const char *ssid = "HONOR X10";    //路由器账号
const char *password = "10086111";  //路由器
ESP8266WebServer server(80);
IPAddress myIP;
int i = 0;//用来判定连接是否超时的累加量
void setup() {
  Serial.begin(115200);  //打开串口
  Serial.println("开始连接");
  
  //调用 WiFi.begin()函数，开始连接接入点
  WiFi.begin(ssid, password);
  Serial.print("正在连接到");
  Serial.print(ssid);
  
  //这里的循环用来判断是否连接成功的。连接过程中每隔500毫秒会检查一次是否连接成功，，并打一个点表示正在连接中
  //连接成功后会给出提示，但是若60秒后还是没有连接上，则会提示超时
  while (WiFi.status() != WL_CONNECTED) {
    i++;
    delay(500);
    Serial.print(".");
    if (i > 120) { //60秒后如果还是连接不上，就判定为连接超时
      Serial.print("连接超时！请检查网络环境");
      break;
    }
  }
  Serial.println("网络连接成功");
  
  //这一部分用来输出连接网络的基本信息
  Serial.print("当前工作模式:");     // 告知用户设备当前工作模式
  Serial.println(WiFi.getMode());
  Serial.print("连接到的接入点名字:");
  Serial.println(ssid);            // 告知用户建立的接入点WiFi名
  Serial.print("连接到的接入点密码:");
  Serial.println(password);        // 告知用户建立的接入点WiFi密码
  Serial.print("无线终端模式成功开启，网络连接成功");
//  Serial.begin(115200);  //打开串口
//  WiFi.mode(WIFI_STA);   //设置无线工作模式为无线终端模式
//  WiFi.begin(ssid, password);
//  wifi_station_dhcpc_stop();  //关闭dhcp
//  struct ip_info info;        //设置静态IP
//  IP4_ADDR(&info.ip, 192, 168, 1, 189);
//  IP4_ADDR(&info.gw, 192, 168, 1, 1);
//  IP4_ADDR(&info.netmask, 255, 255, 255, 0);
//  wifi_set_ip_info(STATION_IF, &info);
//  //WiFi
//  Serial.printf("连接至%s", ssid);
  // SPI initialization
  pinMode(CS_PIN, OUTPUT);
  pinMode(RST_PIN, OUTPUT);
  pinMode(DC_PIN, OUTPUT);
  pinMode(BUSY_PIN, INPUT);
  SPI.begin();
  //连接成功
  Serial.println("\r\nIP地址: ");
  Serial.print(myIP = WiFi.localIP());
  //开启DNS
  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS已开启");
  }

  server.on("/", handleRoot);
  server.on("/styles.css", sendCSS);
  server.on("/processingA.js", sendJS_A);
  server.on("/processingB.js", sendJS_B);
  server.on("/processingC.js", sendJS_C);
  server.on("/processingD.js", sendJS_D);
  server.on("/LOAD", EPD_Load);
  server.on("/EPD", EPD_Init);
  server.on("/NEXT", EPD_Next);
  server.on("/SHOW", EPD_Show);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP服务已经开启");
}

void loop() {
  server.handleClient();
}

void EPD_Init() {
  EPD_dispIndex = ((int)server.arg(0)[0] - 'a') + (((int)server.arg(0)[1] - 'a') << 4);
  // Print log message: initialization of e-Paper (e-Paper's type)
  Serial.printf("EPD %s\r\n", EPD_dispMass[EPD_dispIndex].title);

  // Initialization
  EPD_dispInit();
  server.send(200, "text/plain", "Init ok\r\n");
}

void EPD_Load() {
  //server.arg(0) = data+data.length+'LOAD'
  String p = server.arg(0);
  Serial.print(p);
  if (p.endsWith("LOAD")) {
    int index = p.length() - 8;
    int L = ((int)p[index] - 'a') + (((int)p[index + 1] - 'a') << 4) + (((int)p[index + 2] - 'a') << 8) + (((int)p[index + 3] - 'a') << 12);
    if (L == (p.length() - 8)) {
      Serial.println("LOAD");
      // if there is loading function for current channel (black or red)
      // Load data into the e-Paper
      if (EPD_dispLoad != 0) EPD_dispLoad();
    }
  }
  server.send(200, "text/plain", "Load ok\r\n");
}

void EPD_Next() {
  Serial.println("NEXT");

  // Instruction code for for writting data into
  // e-Paper's memory
  int code = EPD_dispMass[EPD_dispIndex].next;

  // If the instruction code isn't '-1', then...
  if (code != -1) {
    // Do the selection of the next data channel
    EPD_SendCommand(code);
    delay(2);
  }
  // Setup the function for loading choosen channel's data
  EPD_dispLoad = EPD_dispMass[EPD_dispIndex].chRd;

  server.send(200, "text/plain", "Next ok\r\n");
}

void EPD_Show() {
  Serial.println("\r\nSHOW\r\n");
  // Show results and Sleep
  EPD_dispMass[EPD_dispIndex].show();
  server.send(200, "text/plain", "Show ok\r\n");
}

void handleNotFound() {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(200, "text/plain", message);
  Serial.print("Unknown URI: ");
  Serial.println(server.uri());
}
